<?php

namespace app\api\controller;

use app\common\Aliyun\demo\SendSms;
use app\common\library\common;
use think\db\exception\DataNotFoundException;
use think\facade\Db;
use think\Request;


class Levelnotify extends Wap
{

    /**
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        if (request()->isPost()) {
            // 获取微信回调的数据
            $notifiedData = file_get_contents('php://input');
            file_put_contents('Recharge.text', $notifiedData, FILE_APPEND);
            //XML格式转换
            $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
            $xmlObj = json_decode(json_encode($xmlObj), true);
            $sign_return = $xmlObj['sign'];


            //支付成功
            if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
                unset($xmlObj['sign']);
                $wxapp = Db::name('mini_match')->where('id', 1)->find();
                if ($wxapp['app_id'] && $wxapp['wc_hid'] && $wxapp['api_key']) {
                    $key = $wxapp['api_key'];
                }
                $sign = $this->appgetSign($xmlObj, $key);

                if ($sign === $sign_return) {
                    $order = Db::name('customer_level_order')->where('order_on', $xmlObj['out_trade_no'])->find();
                    if ($order['pay_time'] > 0) {
                        $this->returnCode(true, 'OK');
                    }

                    $order['status'] = 1;
                    $order['pay_time'] = time();
                    $order['pay_type'] = 1;
                    if (Db::name('customer_level_order')->where('order_on', $xmlObj['out_trade_no'])->update($order)) {
                        $user = Db::name('member')->where('id', $order['user_id'])->find();
                        $balance['balance'] = $user['balance'] + $order['price'] + $order['give_price'];

                        Db::name('member')->where('id', $order['user_id'])->update($balance);

                        $userbalance = array(
                            'store_id' => $order['store_id'],
                            'price' => $order['price'] + $order['give_price'],
                            'type' => 1,
                            'status' => $order['order_on'],
                            'before_price' => $user['balance'],
                            'aater_price' => $balance['balance'],
                            'create_time' => time(),
                            'user_id' => $user['id'],
                            'content' => "充值余额",
                        );
                        Db::name('customer_user_balance')->insert($userbalance);
                        $count = "充值余额";
                        $this->distribution($order['store_id'], $order['price'], 2, $count,$order['id']);
                        $this->returnCode(true, 'OK');
                    }

                }
            }
        }
    }

    /**
     * 回调信息
     * @param $returnCode
     * @param $msg
     * @return void
     */
    private function returnCode($returnCode = true, $msg = null)
    {
        // 返回状态
        $return = [
            'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
            'return_msg' => $msg ?: 'OK',
        ];
        // 记录日志

        die($this->toXml($return));
    }

    /**
     * @content 格式化参数格式化成url参数  生成签名sign
     * @param $Obj
     * @param $appwxpay_key
     * @return string
     */
    public function appgetSign($Obj, $appwxpay_key)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        if ($appwxpay_key) {
            $String = $String . "&key=" . $appwxpay_key;
        }
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }


    /**
     * @content 将数组转成uri字符串
     * @param $paraMap
     * @param $urlencode
     * @return false|string
     */
    public function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 输出xml字符
     * @param $values
     * @return bool|string
     */
    private function toXml($values)
    {
        if (!is_array($values)
            || count($values) <= 0
        ) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}